﻿using FDStudio.Core.Container;
using FDStudio.Core.Entities;
using FDStudio.Core.Runtime;
using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;

namespace FDStudio.Core.Repositories
{
    /*
     CreatedOn: 2018-01-26
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 读写仓储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ReadWriteRepository<T> : PagedReadRepository<T>, IWriteOnlyRepository<T> where T : class, IEntity
    {
        private IContainer _container;

        public ReadWriteRepository()
        {
            _container = RuntimeContext.Current.Container;
        }

        private IWriteOnlyRepositoryContext _writeOnlyContext => _container.Resove<IWriteOnlyRepositoryContext>();

        public override C RepositoryContext<C>()
        {
            var type = typeof(C);
            if (type == typeof(IReadOnlyRepositoryContext) || type.GetInterfaces().Contains(typeof(IReadOnlyRepositoryContext)))
                return base.RepositoryContext<C>();
            return (C)_writeOnlyContext;
        }

        public bool Add(T model)
        {
            return _writeOnlyContext.Add(model);
        }

        public bool Delete(long Id)
        {
            return _writeOnlyContext.Delete<T>(t => t.Id == Id);
        }

        public bool Delete(T model)
        {
            return _writeOnlyContext.Delete(model);
        }

        public bool Delete(Expression<Func<T, bool>> condition)
        {
            return _writeOnlyContext.Delete(condition);
        }

        public int ExecuteNonQuery(string sql, object parameter, CommandType commandType)
        {
            return _writeOnlyContext.ExecuteNonQuery(sql, parameter, commandType);
        }

        public bool Update(T model)
        {
            return _writeOnlyContext.Update(model);
        }

        public void BeginTransaction()
        {
            _writeOnlyContext.BeginTransaction();
        }

        public void CommitTransaction()
        {
            _writeOnlyContext.CommitTransaction();
        }

        public void RollbackTransaction()
        {
            _writeOnlyContext.RollbackTransaction();
        }
    }
}
